<template>
<div @click="category.showTree = false">
    <el-form label-position="top" :inline="true" v-model="positionForm" >
        <el-row >

            <el-col :span="5" v-show ="visible == true && type == '0' || type == '2' || type == '3' || type == '4'">
                <el-form-item label="统计日期：">
                    <el-date-picker
                            size="small"
                            @change = "changeDateRange"
                            v-model="positionForm.timeRange"
                            type="daterange"
                            :start-placeholder="placeHolderText.split(' - ')[0]"
                            :end-placeholder="placeHolderText.split(' - ')[1]"
                            :placeholder="placeHolderText">
                    </el-date-picker>
                </el-form-item>
            </el-col>

            <el-col :span="5" v-show ="visible == true && type == '1'">
                <el-form-item label="统计日期：">
                    <el-date-picker
                            size="small"
                            @change = "changeDate"
                            v-model="positionForm.time"
                            type="date"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
            </el-col>

            <el-col :span="5" v-show ="visible == true && type == '3'">
                <el-form-item label="客户类型：">
                     <el-select  size="small" v-model="newValue" placeholder="请选择">
                        <el-option
                          v-for="item in options"
                          :key="item.id"
                          :label="item.label"
                          @change="handleChange"
                          :value="item.label">
                        </el-option>
                      </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="5" v-show ="visible == true && type == '0' || type == '1' || type == '2'">
                <el-form-item label="客户类型：">
                    <el-input v-model="category.name" prefix-icon="el-icon-caret-bottom" placeholder="请选择客户类型"  size="small"></el-input>
                    <div @click.stop="category.showTree=!category.showTree"
                         style="position: absolute;top:3px;left:0;z-index: 10;width: 100%;height: 30px;">
                        <div v-show="category.showTree" class="department-tree-select inline-tree" >
                            <el-tree :data="category.data"
                                     show-checkbox
                                     default-expand-all
                                     node-key="id"
                                     ref="searchCategoryTree"
                                     @check-change="handleCheckChange"
                                     :props="defaultProps">
                            </el-tree>
                        </div>
                    </div>
                </el-form-item>
            </el-col>

            <el-col :span="5"  v-show ="visible == true && type == '2'">
                <el-form-item label="是否有效联系：">
                    <el-select  size="small" v-model="filter.contactState" placeholder="请选择">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="是" value=1></el-option>
                        <el-option label="否" value=0></el-option>
                    </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="5">
                <el-form-item label="部门 / 团队 / 人员：">
                    <div>
                        <el-input v-model="positionForm.departmentName" :disabled="departmentDisable" size="small" prefix-icon="el-icon-caret-bottom" placeholder="请选择部门"></el-input>
                        <div @click.stop="positionShowTree"
                             style="position: absolute;top:3px;left:0;z-index: 10;width: 100%;height: 30px;">
                            <div v-if="positionForm.showTree && !departmentDisable" class="department-tree-select" >
                                <el-tree size="small"
                                        :data="departmentTree"
                                         :props="departmentTreeProps"
                                         @check-change="handleSearchCheckChange"
                                         node-key="key" 
                                         ref="searchTree"
                                         show-checkbox
                                         accordion
                                         highlight-current
                                         check-strictly
                                         >
                                </el-tree>
                            </div>
                        </div>
                    </div>
                </el-form-item>
            </el-col>
            <!--:load="loadNode" check-strictly highlight-current lazy accordion-->

            <el-col :span="24">
                <div class="search-btn">
                	<el-button @click="clearFilter" type="primary" icon="el-icon-delete" size="small">清空筛选条件</el-button>
                    <el-button size="small" type="primary" icon="el-icon-search" @click="filterData">查询</el-button>
                </div>
            </el-col>
        </el-row>
    </el-form>
</div>
    

</template>

<script>
    import axios from '~plugins/axios';
    import { getCookie } from '~/utils/auth'
    import {mapGetters, mapActions, mapMutations} from 'vuex';
    import * as types from '../store/mutation-types/user_login/index';
    import { months ,getTime ,years ,getYesterday,getDate,getLevelName,getSevenDaysBefore } from '~/utils/auth'
    import { hasTargetNode,getClickTarget } from '../assets/js/common.js';
    import Vue from 'vue'
    import {Row, Col, Form, FormItem, DatePicker, Select, Option, ButtonGroup, Button,Input, Tree } from 'element-ui'

    Vue.use(Row);
    Vue.use(Col);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(DatePicker);
    Vue.use(Select);
    Vue.use(Option);
    Vue.use(ButtonGroup);
    Vue.use(Button);
    Vue.use(Input);
    Vue.use(Tree);

    export default {
        data () {
            return {
                placeHolderText:"开始日期 - 结束日期",
                departmentTree: [],
                departmentDisable: true,
                departmentTreeProps: {
                    label: 'label',
                    children: 'children'
                },
                positionForm: {
                    timeRange: "",
                    time: new Date(),
                    department: '',
                    showTree: false,
                    departmentName: ''
                },
                filter: {
                    dateRange: [],
                    date:null,
                    deptId: "",
                    usId:"",
                    customerlevel:'',
                    level:'',  
                    contactState:"",   //是否有效联系
                    flag:'',
                    category:[],
                    teamName:"",
                    userName:"",
                    moreUser:false,
                },
                newcustomerlevel:"",
                newValue:"3类（认可价格和服务）",
                options:[],
                category: {
                    name: '全部',
                    showTree: false,
                    data:[{
                        id: 0,
                        label: '全部',
                        children: [{    //预留children
                            id: 1,
                            label: '暂无数据'
                        }]
                    }]
                },
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                checkedUserId:[],
                checkedUserName:[],
            }
        },
        props: {
            'visible' : {
                default: false
            },
            'type' : {
                default: 0
            },
            'cateShow' : {
                default: false
            }
        },
        watch:{
            "positionForm.showTree"(){
                if(this.positionForm.showTree == false){
                    if(this.filter.deptId == "" && this.filter.usId == ""){
                        this.cookieUserData();
                    }
                }
            },
            cateShow(){
                this.category.showTree = false;
                this.positionForm.showTree = false;
            },
            checkedUserId(){
                this.filter.moreUser = this.checkedUserId.length > 1 ? true:false;
            },
            newValue(){
                switch(this.newValue){

                    case "3类（认可价格和服务）":
                    this.filter.customerlevel = this.options[0].id;
                    break;

                    case "4类（7天内付款）":
                    this.filter.customerlevel = this.options[1].id;
                    break;

                    case "5类（24小时内办理）":
                    this.filter.customerlevel = this.options[2].id;
                    break;

                }
            }
        },
        mounted () {
            this.cookieUserData();
            this.getTreeJson();
            
        },
        computed : {
            ...mapGetters({
                'userData' : 'getUserData'
            })
        },
        methods: {
            //搜索条件加入store
            setFilterCookie(){
                this.filter.date = this.positionForm.time;
                let data = this.filter;
                let category = this.category.name;
                let categoryB = this.newValue;
                let contact = this.filter.contactState;
                let dept = this.positionForm.departmentName;
                switch (this.type){
                    case 0:
                        this.$store.commit('REPORT_ADD_FILTER',{data});
                        this.$store.commit('REPORT_ADD_CATEGORY',{data:category});
                        this.$store.commit('REPORT_ADD_DEPT',{data:dept});
                        break;
                    case 1:
                        this.$store.commit('REPORT_OWNER_FILTER',{data});
                        this.$store.commit('REPORT_OWNER_CATEGORY',{data:category});
                        this.$store.commit('REPORT_OWNER_DEPT',{data:dept});
                        break;
                    case 2:
                        this.$store.commit('REPORT_FOLLOW_FILTER',{data});
                        this.$store.commit('REPORT_FOLLOW_CATEGORY',{data:category});
                        this.$store.commit('REPORT_FOLLOW_DEPT',{data:dept});
                        this.$store.commit('REPORT_FOLLOW_CONTACT',{data:contact});
                        break;
                    case 3:
                        this.$store.commit('REPORT_DESTINATION_FILTER',{data});
                        this.$store.commit('REPORT_DESTINATION_CATEGORY',{data:categoryB});
                        this.$store.commit('REPORT_DESTINATION_DEPT',{data:dept});
                        break;
                    case 4:
                        this.$store.commit('REPORT_ONLINE_FILTER',{data});
                        this.$store.commit('REPORT_ONLINE_DEPT',{data:dept});
                        break;
                    default:
                        this.$store.commit('REPORT_ADD_FILTER',{data});
                        this.$store.commit('REPORT_ADD_CATEGORY',{data:category});
                        this.$store.commit('REPORT_ADD_DEPT',{data:dept});
                        break;
                }
                
            },
            //获取当前用户信息
            cookieUserData(){
                let userData = getCookie('userData');
                if(userData) {
                    if(JSON.parse(userData).leaderType == "1"){//leaderType = 1则为管理者账号
                        this.departmentDisable = false;
                        this.positionForm.department = this.userData.departmentId || JSON.parse(userData).departmentId;
                        this.positionForm.departmentName = JSON.parse(userData).departmentName;
                        this.filter.teamName = this.userData.departmentName || JSON.parse(userData).departmentName;
                        this.filter.usId = "";
                        this.filter.deptId = this.userData.departmentId || JSON.parse(userData).departmentId || "";
                        this.filter.flag = "0";
                        
                    }else{
                        this.departmentDisable = true;
                        this.positionForm.department = this.userData.id || JSON.parse(userData).id;
                        this.positionForm.departmentName = this.userData.name || JSON.parse(userData).name;
                        this.filter.usId = this.userData.id || JSON.parse(userData).id || "";
                        this.filter.level = "99";
                        this.filter.userName = this.userData.name || JSON.parse(userData).name;
                        this.filter.flag = "1";//人员
                    }
                    
                }
            },

            positionShowTree(){
                this.positionForm.showTree = !this.positionForm.showTree;
                this.positionForm.departmentName = "";
                this.positionForm.department = "";
                this.filter.usId = "";
                this.filter.deptId = "";
                this.checkedUserId = [];
                this.checkedUserName = [];
            },
            //递归遍历Tree加入唯一key
            extendTree(data){
                let item = data;
                item.forEach((n)=>{
                    n.key = n.flag+'-'+n.id;
                    if(n.children){
                        this.extendTree(n.children)
                    }
                })
                return item;
            },
            getTreeJson(){
              if(this.departmentTree.length == 0){
                axios.get(process.env.baseUrl + '/department/getOwnerDeptWithUser', {params:{ flag:1}})
                  .then((ret)=>{
                    let success = ret.data.successed;
                    if(success){
                        if(ret.data && ret.data.data){
                            let list = this.extendTree(ret.data.data)
                            this.departmentTree = list;
                            // console.log(this.departmentTree)
                            if(!this.departmentDisable){ //如果是部门则选tree的flag
                                this.filter.flag = this.departmentTree[0].flag;
                            }
                            this.filterData("first")//请求初始化数据
                        }
                    }
                })
              }
            },

            handleChange(){
            },

            changeDate(val) {
                this.filter.dateRange = [this.positionForm.time,this.positionForm.time];
            },
            changeDateRange(val) {
                this.filter.dateRange = this.positionForm.timeRange;
            },
            filterData(times) {
                if(times == 'first'){
                    //取store
                    switch (this.type){
                        case 0:
                            let filterA = this.$store.getters.reportAddFilter;
                            if(filterA){
                                this.positionForm.timeRange = filterA.dateRange;
                                this.category.name = this.$store.getters.reportAddCategory;
                                this.positionForm.departmentName = this.$store.getters.reportAddDept;
                                this.filter = filterA;
                            } 
                            break;
                        case 1:
                            let filterB = this.$store.getters.reportOwnerFilter;
                            if(filterB){
                                this.positionForm.time = filterB.date;
                                this.category.name = this.$store.getters.reportOwnerCategory;
                                this.positionForm.departmentName = this.$store.getters.reportOwnerDept;
                                this.filter = filterB;
                            } 
                            break;
                        case 2:
                            let filterC = this.$store.getters.reportFollowFilter;
                            if(filterC){
                                this.positionForm.timeRange = filterC.dateRange;
                                this.category.name = this.$store.getters.reportFollowCategory;
                                this.positionForm.departmentName = this.$store.getters.reportFollowDept;
                                this.filter.contactState = this.$store.getters.reportFollowContact;
                                this.filter = filterC;
                            } 
                            break;
                        case 3:
                            let filterD = this.$store.getters.reportDestinationFilter;
                            if(filterD){
                                this.positionForm.timeRange = filterD.dateRange;
                                this.newValue = this.$store.getters.reportDestinationCategory;
                                this.positionForm.departmentName = this.$store.getters.reportDestinationDept;
                                this.filter = filterD;
                            } 
                            break;
                        case 4:
                            let filterE = this.$store.getters.reportOnlineFilter;
                            if(filterE){
                                this.positionForm.timeRange = filterE.dateRange;
                                this.category.name = this.$store.getters.reportOnlineCategory;
                                this.positionForm.departmentName = this.$store.getters.reportOnlineDept;
                                this.filter = filterE;
                            } 
                            break;
                        default:
                            let filterF = this.$store.getters.reportAddFilter;
                            if(filterF){
                                this.positionForm.timeRange = filterF.dateRange;
                                this.category.name = this.$store.getters.reportAddCategory;
                                this.positionForm.departmentName = this.$store.getters.reportAddDept;
                                this.filter = filterA;
                            }
                            break;
                    }
                }else{
                    this.setFilterCookie();
                }
                
                this.$parent['getFilterData'](this.filter,times);
            },
			
			
			getSalesCategoryList(){
				// 获取客户类别等级列表
	            this.$store.dispatch('getSalesCategoryList')
	            .then((response) => {
	                if(response.data && response.data.data ){
	                    var data = response.data.data;
	                    this.category.data[0].children=[];
	
	                    for(var i=0;i< data.length;i++){
	                        if(this.type == "0" || this.type == "3"){
	                            if(data[i].key == 340 || data[i].key ==341 || data[i].key ==342 ){
	                                this.category.data[0].children.push({id: data[i].key , label : data[i].value});
	                            }
	                        }else{
	                            this.category.data[0].children.push({id: data[i].key , label : data[i].value});
	                            //默认全部
	                            this.filter.customerlevel+=(data[i].key+(i<data.length-1?',':''));
	                        }  
	                    }
	                    let list = this.category.data[0].children;
	                    for(let n = 0; n<list.length; n++){
	                        if(this.type == "0"){
	                            this.filter.customerlevel+=(list[n].id+(n<list.length-1?',':''));
	                        }else if(this.type == "3"){
	                            this.filter.customerlevel=list[0].id;
	                        }
	                    }
						//this.newcustomerlevel = this.filter.customerlevel
	                    this.options = this.category.data[0].children;
	                    this.filter.date = this.positionForm.time;
	                    //this.filterData("first")
	                }
	            })
			},
			
			clearFilter(){
				console.log(11)
				this.filter= {
                    dateRange: [],
                    date:null,
                    deptId: "",
                    usId:"",
                    customerlevel:'',
                    level:'',  
                    contactState:"",   //是否有效联系
                    flag:'',
                    category:[],
                    teamName:"",
                    userName:"",
                    moreUser:false,
                }
				this.positionForm= {
                    timeRange: "",
                    time: new Date(),
                    department: '',
                    showTree: false,
                    departmentName: ''
                }
				this.newValue="3类（认可价格和服务）"
				this.category= {
                    name: '全部',
                    showTree: false,
                    data:[{
                        id: 0,
                        label: '全部',
                        children: [{    //预留children
                            id: 1,
                            label: '暂无数据'
                        }]
                    }]
                }
				this.getSalesCategoryList()
				this.cookieUserData()
			},
			
            //部门选中回调
            handleSearchCheckChange(data,checked) {
                if(checked) {
                    //如果不是同级就清空
                    if(this.filter.flag != data.flag){
                        this.$refs.searchTree.setCheckedKeys([]);
                    }
                    this.filter.flag = data.flag;
                    this.filter.level = data.level;
                    if(data.flag == 1){//1人员
                        //this.filter.usId = data.id;
                        this.filter.deptId = "";
                        this.filter.userName = data.label;
                        this.checkedUserName.push(data.label);//人员名称
                        this.checkedUserId.push(data.id);//人员id
                        this.filter.usId = this.checkedUserId.join(',');
                        this.positionForm.departmentName = this.checkedUserName.join(' / ');
                    }else{//0部门
                        this.filter.usId = "";
                        this.filter.deptId = data.id;
                        this.filter.teamName = data.label;
                        this.filter.userName = "";
                        this.$refs.searchTree.setCheckedKeys([]);//部门不支持多选

                        this.checkedUserId = [];
                        this.checkedUserName = [];
                
                        this.positionForm.department = data.id;
                        this.positionForm.departmentName = data.label;
                    }
                    
                    //this.positionForm.showTree = !this.positionForm.showTree;
                    this.$refs.searchTree.setChecked(data,true)

                }else{
                    if(data.flag == 1){//1人员
                        this.checkedUserId.pop(data.id);
                        this.checkedUserName.pop(data.label);
                        this.filter.usId = this.checkedUserId.join(',');
                        this.positionForm.departmentName = this.checkedUserName.join(' / ');
                    }
                }

            },
            //客户分类选中回调
            handleCheckChange(data,checked) {
                this.category.name ='';
                var checkedId = this.$refs.searchCategoryTree.getCheckedKeys(data,true);
                var checkedName = [];
                if(checkedId.length == this.category.data[0].children.length) {
                    this.category.name = '全部'
                }else {
                    for(var i=0;i<checkedId.length;i++){
                        checkedName.push(getLevelName(checkedId[i]));
                    }
                    this.category.name = checkedName.join(' / ');
                }
                this.filter.customerlevel = checkedId.join(',');
                this.filter.category = checkedName;
            },
            //隐藏客户分类
            treeBlurHide(){
                this.category.showTree = false;
            }
        },
        created(){
            //默认七天
            //this.placeHolderText = getSevenDaysBefore(new Date()) + ' - ' + getYesterday(new Date());
            //默认当天
            this.placeHolderText = getDate(new Date()) + ' - ' + getDate(new Date());
            this.getSalesCategoryList()
        }
    }
</script>


<style scoped lang="scss">
    .search-btn {
        margin-bottom: 20px;
    }
    .department-tree-select{
        width: 130%;
        max-height: 400px;
        overflow: auto;
    }
        .el-form {
			.el-form-item {
				width: 70%
			}
			
			.operator-btn {
				text-align: center;
				padding: 0 10px;
			}
			.el-cascader,
			.el-date-picker {
				width: 100%
			}
		}
</style>
